import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store' // 需要导入store
import {
	getToken
} from '@/utils/auth' // 假设您有getToken方法

// 0. 如果使用模块化机制编程，导入Vue和VueRouter，要调用 Vue.use(VueRouter)
Vue.use(VueRouter)

// 不需要token认证的白名单路由
const whiteList = ['/login', '/enroll']

//1.创建路由组件
//2.路由与组件进行映射

const routes = [{
		path: '/login',
		component: () => import('../views/login.vue')
	},
	{
		path: '/enroll',
		component: () => import('../views/Enroll.vue')
	},
	{
		path: '/userInfo',
		component: () => import('../views/UserInfo.vue')
	},

	// 主布局路由 - 使用MainPage.vue作为布局
	{
		path: '/',
		component: () => import('../views/MainPage.vue'),
		redirect: to => {
			const userType = store.state.user?.usertype
			switch (userType) {
				case 'admin':
					return '/admin'
				case 'doctor':
					return '/doctor'
				case 'patient':
					return '/patient'
				default:
					return '/login'
			}
		},
		meta: {
			requiresAuth: true
		},
		children: [
			// 管理员路由
			{
				path: '/admin',
				name: 'adminHome',
				component: () => import('../views/admin/AdminMain.vue'),
				meta: {
					userType: 'admin'
				}
			},
			{
				path: '/admin/deptDictManagement',
				name: 'deptDictManagement',
				component: () => import('../views/admin/DeptDictManagement.vue'),
				meta: {
					userType: 'admin'
				}
			},
			{
				path: '/admin/diseaseDictManagement',
				name: 'diseaseDictManagement',
				component: () => import('../views/admin/DiseaseDictManagement.vue'),
				meta: {
					userType: 'admin'
				}
			},
			{
				path: '/admin/examItemDictManagement',
				name: 'examItemDictManagement',
				component: () => import('../views/admin/ExamItemDictManagement.vue'),
				meta: {
					userType: 'admin'
				}
			},
			{
				path: '/admin/drugDictManagement',
				name: 'drugDictManagement',
				component: () => import('../views/admin/DrugDictManagement.vue'),
				meta: {
					userType: 'admin'
				}
			},
			{
				path: '/admin/operationLogManagement',
				name: 'operationLogManagement',
				component: () => import('../views/admin/OperationLogManagement.vue'),
				meta: {
					userType: 'admin'
				}
			},
			// 医生路由
			{
				path: '/doctor',
				name: 'doctorHome',
				component: () => import('../views/doctor/DoctorMain.vue'),
				meta: {
					userType: 'doctor'
				}
			},
			{
				path: '/doctor/patients',
				name: 'doctorPatients',
				component: () => import('../views/doctor/DoctorPatients.vue'),
				meta: {
					userType: 'doctor'
				}
			},
			{
				path: '/doctor/getMedicalRecord',
				name: 'doctorGetMedicalRecord',
				label: '查看病历',
				component: () => import('../views/doctor/GetMedicalRecord.vue'),
				meta: {
					userType: 'doctor'
				}
			},
			{
				path: '/doctor/getMedicalReport',
				name: 'doctorGetMedicalReport',
				label: '查看检查',
				component: () => import('../views/doctor/GetMedicalReport.vue'),
				meta: {
					userType: 'doctor'
				}
			}, ,
			{
				path: '/doctor/newMedicalRecord',
				name: 'doctorNewMedicalRecord',
				label: '新建病历',
				component: () => import('../views/doctor/NewMedicalRecord.vue'),
				meta: {
					userType: 'doctor'
				}
			},
			{
				path: '/doctor/newMedicalReport',
				name: 'doctorNewMedicalReport',
				label: '新建检查',
				component: () => import('../views/doctor/NewMedicalReport.vue'),
				meta: {
					userType: 'doctor'
				}
			},
			{
				path: '/doctor/createPrescription',
				name: 'createPrescription',
				label: '查询新建',
				component: () => import('../views/doctor/CreatePrescription.vue'),
				meta: {
					userType: 'doctor'
				}
			},
			{
				path: '/doctor/myPrescription',
				name: 'myPrescription',
				label: '我的处方',
				component: () => import('../views/doctor/MyPrescription.vue'),
				meta: {
					userType: 'doctor'
				}
			},
			// 患者路由 - 所有患者相关路由都在同一层级
			{
				path: '/patient',
				name: 'patientHome',
				component: () => import('../views/patient/PatientMain.vue'),
				meta: {
					userType: 'patient'
				}
			},
			{
				/*患者预约挂号*/
				path: '/patient/appointment',
				name: 'patientAppointment',
				component: () => import('../views/patient/PatientAppointment.vue'),
				meta: {
					userType: 'patient'
				}
			},
			{
				/*患者病历总记录*/
				path: '/patient/patientRecord',
				name: 'PatientRecord',
				component: () => import('../views/patient/PatientRecord.vue'),
				meta: {
					userType: 'patient'
				}
			},
			{
				/*患者授权病历*/
				path: '/patient/authorization',
				name: 'authorization',
				component: () => import('../views/patient/PatientAuthorization.vue'),
				meta: {
					userType: 'patient'
				}
			},
			{
				/*患者检查报告总记录*/
				path: '/patient/patientReport',
				name: 'patientReport',
				component: () => import('../views/patient/PatientReport.vue'),
				meta: {
					userType: 'patient'
				}
			},
			{
				path: '/patient/myPrescription',
				name: 'myPrescription',
				component: () => import('../views/patient/MyPrescription.vue'),
				meta: {
					userType: 'patient'
				}
			},
		]
	},
]

//3.创建router实例,传入Routes配置
const router = new VueRouter({
	routes,
	mode: 'history' // 推荐使用history模式
})

//4.创建和挂载根示例
//通过routes参数注入路由，让整个系统都有路由功能


// 路由守卫
router.beforeEach((to, from, next) => {
	console.log('路由守卫 - 从:', from.path, '到:', to.path)
	console.log('Store state:', store.state)
	console.log('Store isLogin:', store.state.isLogin)
	console.log('Store token:', store.state.token)

	// 1. 首先检查是否为相同路由跳转
	if (to.path === from.path && to.name === from.name) {
		console.log('相同路由，取消导航')
		next(false)
		return
	}

	// 2. 检查是否在白名单中
	if (whiteList.includes(to.path)) {
		console.log('白名单路由，直接放行')
		next()
		return
	}

	// 3. 检查是否需要认证
	if (to.matched.some(record => record.meta.requiresAuth)) {
		console.log('需要认证的路由:', to.path)

		// 修复1: 直接使用 store.state，不是 this.$store
		// 修复2: 注意 isLogin 是字符串 '0' 或 '1'，不是数字
		const isLoggedIn = store.state.isLogin === '1'
		const hasToken = store.state.token && store.state.token !== ''

		console.log('登录状态 - isLogin:', store.state.isLogin, '解析为:', isLoggedIn)
		console.log('Token状态:', hasToken)

		if (!isLoggedIn || !hasToken) {
			console.log('未登录或token无效，跳转到登录页')
			next({
				path: '/login',
				query: {
					redirect: to.fullPath
				}
			})
			return
		}

		// 4. 检查用户类型权限
		const userType = store.state.user?.usertype || store.state.usertype
		const requireUserType = to.meta.userType

		console.log('用户类型:', userType, '要求类型:', requireUserType)

		if (requireUserType && requireUserType !== userType) {
			console.log('用户类型不匹配，重定向')
			// 用户类型不匹配，重定向到对应主页
			switch (userType) {
				case 'admin':
					next('/admin')
					break
				case 'doctor':
					next('/doctor')
					break
				case 'patient':
					next('/patient')
					break
				default:
					next('/login')
			}
			return
		}

		console.log('认证通过，允许访问')
		next()
	} else {
		// 不需要认证的路由
		console.log('公开路由，直接放行')
		next()
	}
})
//5.将实例对外暴露
export default router